<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class SettingRegionService
{
    // 列表
    public static function index($data)
    {
        $auth = Auth::instance();
        // 查询region_code不包含-的数据
        $regions = \app\admin\model\Regions::where('region_code', 'not like', '%-%')->select();

        if (!empty($regions)) {
            // 构建子区域查询条件
            $query = \app\admin\model\Regions::where('region_code', 'like', '%-%');

            $conditions = [];
            foreach ($regions as $region) {
                $conditions[] = [
                    'region_code' => ['like', $region['country_code'].'-%'],
                    'region_code' => ['like', '%'.$region['region_code'].'%']
                ];
            }

            // 使用whereOr组合查询条件
            $query->where(function($q) use ($conditions) {
                foreach ($conditions as $condition) {
                    $q->whereOr($condition);
                }
            });

            $allSubRegions = $query->select();

            // 按country_code分组
            $groupedSubRegions = [];
            foreach ($allSubRegions as $subRegion) {
                $groupedSubRegions[$subRegion['country_code']][] = $subRegion;
            }

            foreach ($regions as $key => $region) {
                if (isset($groupedSubRegions[$region['country_code']])) {
                    $filteredSubRegions = array_filter($groupedSubRegions[$region['country_code']],
                        function($subRegion) use ($region) {
                            return strpos($subRegion['region_code'], $region['region_code']) !== false;
                        });

                    if (!empty($filteredSubRegions)) {
                        $regions[$key]['child'] = array_values($filteredSubRegions);
                    }
                }
            }
        }

        return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $regions];
    }


    // 添加
    public static function add($data)
    {
        // 验证规则 region_code，region_name，country_code 不为空且不重复
        $validate = new Validate([
            'region_code' => 'require|unique:regions,region_code',
            'region_name' => 'require|unique:regions,region_name',
            'country_code' => 'require',
        ], [
            'region_code.require' => 'Region code is not empty',
            'region_code.unique' => 'Region code is already exists',
            'region_name.require' => 'Region name is not empty',
            'region_name.unique' => 'Region name is already exists',
            'country_code.require' => 'Country code is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            $result = \app\admin\model\Regions::create($data);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>$result];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code'=>400, 'msg'=>'Database error: '.$e->getMessage(), 'state'=>'DATABASE_ERROR', 'data'=>null];
        }
    }


    // 编辑
    public static function edit($data)
    {
        $auth = Auth::instance();

        // 验证规则 region_code，region_name，country_code 不为空且不重复（注意排除当前记录）
        $validate = new Validate([
            'region_code' => 'require|unique:regions,region_code,' . ($data['id'] ?? 0) . ',id',
            'region_name' => 'require|unique:regions,region_name,' . ($data['id'] ?? 0) . ',id',
            'country_code' => 'require',
        ], [
            'region_code.require' => 'Region code is not empty',
            'region_code.unique' => 'Region code is already exists',
            'region_name.require' => 'Region name is not empty',
            'region_name.unique' => 'Region name is already exists',
            'country_code.require' => 'Country code is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启动事务
        Db::startTrans();
        try {
            $result = \app\admin\model\Regions::update($data);

            if ($result !== false) {
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            // 记录日志
            \think\facade\Log::error('Database error in Regions::edit: ' . $e->getMessage());
            return ['code' => 400, 'msg' => 'Database error occurred', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 删除
    public static function del($data)
    {
        // 验证$data['id']是否为空且为数字
        if (empty($data['id']) || !ctype_digit((string)$data['id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            Db::startTrans(); // 显式开启事务
            $result = \app\admin\model\Regions::destroy($data['id']);

            if ($result) {
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            // 记录日志
            \think\facade\Log::error("Database error in Regions deletion: " . $e->getMessage());
            // 返回通用错误信息
            return ['code' => 400, 'msg' => 'Database error occurred', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }



    // 查询
    public static function select($data)
    {
        // 检查 country_code 是否存在并赋默认值
        $countryCode = isset($data['country_code']) ? $data['country_code'] : '';

        // 安全过滤 country_code（假设是 ISO 国家码，如 CN、US）
        if (!preg_match('/^[A-Z]{0,2}$/i', $countryCode)) {
            return ['code' => 400, 'msg' => 'Invalid country code', 'state' => 'ERROR'];
        }

        // 定义 region_code 常量或直接提取为变量
        $fieldRegionCode = 'region_code';

        // 查询逻辑
        if (empty($countryCode)) {
            $regions = \app\admin\model\Regions::where($fieldRegionCode, 'not like', '%-%')->select();
        } else {
            $regions = \app\admin\model\Regions::where($fieldRegionCode, 'like', "%{$countryCode}-%")->select();
        }

        // 返回结果
        if ($regions) {
            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $regions];
        }

        return ['code' => 204, 'msg' => 'No content', 'state' => 'EMPTY', 'data' => $regions];
    }




    
}
